<script setup>
import { getCurrentInstance, ref } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import { getPage, addSave, editSave, getDetailsByKey, delAdverts } from "@/api/company/advertising";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	type: "",
});

const loading = ref(false);

const getTableData = async (params) => {
	loading.value = true;
	const res = await getPage({
		...params,
	});
	try {
		if (res.code === 200) {
			tableData.value = res.data.records;
			total.value = res.data.total;
		}
	} catch (e) {
		proxy.$modal.msgError(JSON.stringify(e));
	} finally {
		loading.value = false;
	}
};

const search = async () => {
	queryParams.value.pageNum = 1;
	await getTableData(queryParams.value);
};

const add = () => {
	rowId.value = null;
	editVisible.value = true;
};

const total = ref(0);
const rowId = ref(null);
const tableData = ref([]);
const returnImg = (item) => {
	return item ? item[0].accessUrl : "";
};
const handleUpdate = (row) => {
	editVisible.value = true;
	rowId.value = row.id;
};
const handleDelete = (row) => {
	// TODO 删除
	proxy.$modal
		.confirm('是否确认删除名称为"' + row.name + '"的数据项?')
		.then(function () {
			return delAdverts({ id: row.id });
		})
		.then(() => {
			getTableData(queryParams.value);
			proxy.$modal.msgSuccess("删除成功");
		})
		.catch(() => {});
};
const fileList = ref([]);

const onOpen = async () => {
	formData.value.fileUrl = null;
	fileList.value = [];
	if (rowId.value) {
		const res = await getDetailsByKey({ id: rowId.value });
		try {
			if (res.code === 200) {
				formData.value.id = res.data.id;
				formData.value.name = res.data.name;
				formData.value.url = res.data.url;
				formData.value.type = res.data.type;
				formData.value.sort = res.data.sort;
				formData.value.isView = res.data.isView == 1 ? true : false;

				res.data.picFiles.forEach((element) => {
					fileList.value.push({ name: element.originlName, url: element.accessUrl, id: element.id });
					formData.value.fileIds.push(element.id);
				});
			} else {
			}
		} catch (e) {
			console.log(e);
		}
	}
};
const onClose = async () => {
	proxy.resetForm("elForm");
	rowId.value = null;
	clearFile();
};

const fileAction = import.meta.env.VITE_APP_BASE_API + "/adverts/addPicFile";
const photoBeforeUpload = (file) => {
	let isRightSize = file.size / 1024 / 1024 < 20;
	if (!isRightSize) {
		proxy.$modal.msgError("文件大小超过 20MB");
	}
	return isRightSize;
};

const editVisible = ref(false);
const formData = ref({
	// id
	id: null,
	// 名称
	name: "",
	url: "",
	type: "",
	sort: "",
	isView: true,
	// 照片
	fileIds: [],
});
const rules = {
	name: [
		{
			required: true,
			message: "请输入广告名称",
			trigger: "blur",
		},
	],
	url: [
		{
			required: true,
			message: "请输入广告地址",
			trigger: "blur",
		},
	],
	type: [
		{
			required: true,
			message: "请选择广告类型",
			trigger: "blur",
		},
	],
	fileIds: [
		{
			required: true,
			message: "请上传照片",
			trigger: "blur",
		},
	],
};
const clearFile = () => {
	formData.value.fileIds = [];
	proxy.$refs["fileIds"].clearFiles();
};

const uploadSuccess = (response, file, fileList) => {
	if (response.code === 200) {
		fileList.forEach((element) => {
			if (element?.response?.data?.id) {
				formData.value.fileIds.push(element.response.data.id);
			} else {
				formData.value.fileIds.push(element.id);
			}
		});
	} else {
		formData.value.fileIds = [];
	}
};
// 图片删除
const uploadRemove = (response, file, fileList) => {
	formData.value.fileIds = [];
	file.forEach((element) => {
		if (element?.response?.data?.id) {
			formData.value.fileIds.push(element.response.data.id);
		} else {
			formData.value.fileIds.push(element.id);
		}
	});
};
const submitForm = async () => {
	proxy.$refs["elForm"].validate(async (valid) => {
		if (valid) {
			const params = {
				...formData.value,
				picFileIds: formData.value.fileIds,
			};
			params["isView"] = params.isView ? 1 : 0;

			let res;
			if (rowId.value) {
				res = await editSave(params);
			} else {
				delete params.id;
				res = await addSave(params);
			}
			try {
				proxy.$modal.msgSuccess(res.msg);
				cancel("submit");
			} catch (e) {
				proxy.$modal.msgError(JSON.stringify(e));
			}
		}
	});
};
const cancel = (type = "cancel") => {
	proxy.resetForm("elForm");
	rowId.value = null;
	editVisible.value = false;
	if (type === "submit") {
		search();
	}
};
const typeOptions = ref([
	{
		value: 1,
		label: "首页轮播新闻",
	},
	{
		value: 2,
		label: "首页中部广告",
	},
	{
		value: 3,
		label: "友情链接",
	},
]);
search();
</script>

<template>
	<div class="app-container">
		<el-form ref="queryForm" :model="queryParams" inline label-width="100px" @submit.native.prevent>
			<el-form-item label="内容栏目">
				<el-select v-model="queryParams.type" placeholder="请选择广告类型" :style="{ width: '100%' }" clearable>
					<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button :disabled="loading" icon="Search" type="primary" @click="search"></el-button>
				<el-button :disabled="loading" type="primary" @click="add()">添加广告 </el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" label="名称" prop="name" />
			<el-table-column :show-overflow-tooltip="true" label="图片" prop="picFiles" width="140">
				<template #default="scope">
					<img :src="returnImg(scope.row.picFiles)" style="max-width: 130px; height: 60px" />
				</template>
			</el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="广告类型" prop="type" width="240">
				<template #default="scope">
					{{ scope.row.type == 1 ? "首页轮播新闻" : scope.row.type == 2 ? "首页中部广告" : "友情链接" }}
				</template>
			</el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="链接地址" prop="url" width="240" />
			<el-table-column :show-overflow-tooltip="true" label="是否显示" prop="isView" width="240">
				<template #default="scope">
					{{ scope.row.isView ? "是" : "否" }}
				</template>
			</el-table-column>
			<el-table-column :show-overflow-tooltip="true" label="排序值" prop="sort" width="160" />
			<el-table-column :show-overflow-tooltip="true" label="添加时间" prop="createTime" width="160" />
			<el-table-column class-name="small-padding fixed-width" label="操作" width="160">
				<template #default="scope">
					<el-button icon="Edit" link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
					<el-button icon="Delete" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="search"></pagination>

		<el-dialog :title="rowId ? '编辑广告' : '添加广告'" v-model="editVisible" append-to-body destroy-on-close center @open="onOpen" @close="onClose">
			<el-form ref="elForm" :model="formData" label-width="100px" :rules="rules">
				<el-form-item label="名称" prop="name">
					<el-input v-model="formData.name" :style="{ width: '100%' }" clearable placeholder="请输入广告名称"></el-input>
				</el-form-item>
				<el-form-item label="链接地址" prop="url">
					<el-input v-model="formData.url" :style="{ width: '100%' }" clearable placeholder="请输入链接地址"></el-input>
				</el-form-item>
				<el-form-item label="类型" prop="type">
					<el-select v-model="formData.type" placeholder="请选择类型" :style="{ width: '100%' }">
						<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>

				<el-form-item label="背景图片" prop="fileIds" required>
					<el-upload
						ref="fileIds"
						:accept="'.jpg,.jpeg,.png'"
						:action="fileAction"
						:before-upload="photoBeforeUpload"
						:headers="{
							Authorization: 'Bearer ' + getToken(),
						}"
						:list-type="'picture'"
						:file-list="fileList"
						:limit="1"
						:on-success="uploadSuccess"
						:on-remove="uploadRemove">
						<template #tip>
							<div class="el-upload__tip text-red">单次只能上传一张照片，如需更换请清空上传</div>
						</template>
						<el-button icon="Upload" :size="'small'" type="primary">点击上传 </el-button>
						<el-button size="small" type="warning" @click.stop="clearFile">清空上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="排序值" prop="sort">
					<el-input v-model="formData.sort" type="number" placeholder="请输入排序值"></el-input>
				</el-form-item>
				<el-form-item label="是否显示" prop="isView">
					<el-switch v-model="formData.isView" active-text="显示" inactive-text="不显示" inline-prompt />
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">提交</el-button>
					<el-button @click="cancel('cancel')">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped></style>
